package cn.com.self.apis.portal.config;

import cn.com.self.apis.portal.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * openid拦截类
 *
 * @Description
 */
@Component
public class UserRedistFilter extends HandlerInterceptorAdapter {

    @Autowired
    private RedisUtils redisUtils;
    @Value("${requestHost}")
    public String requestHostValue;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            response.addHeader("x-frame-options","SAMEORIGIN");
            //获取头部Authorization
            String userId = request.getHeader("Authorization");
            String requestHost  = request.getHeader("host");
            System.out.println("requestHost==="+requestHost);

            if (requestHost != null&&!requestHost.contains(requestHostValue)) {
                response.setStatus(403);
                return false;
            }
            if (userId!=null){
                System.out.print("接收的头部参数====Authorization"+userId);
                String userInfo = redisUtils.get(userId).toString();
                //缓存中存在用户数据说明用户还处于登录状态
                if (userInfo!=null) {
                    return true;
                } else {
                    response.sendError(602, "用户id失效，请重新登录!");
                    return false;
                }
            }else{
                return true;
            }


        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(603, "userId");
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
            handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
    }

    private boolean checkBlankList(String host){
        if(host.contains("10.160.79.")){
            return true;
        }
        return false;
    }

}